package com.suse.service.community.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.suse.common.base.model.entity.Page;
import com.suse.service.community.constant.EntityTypeConstant;
import com.suse.service.community.entity.DiscussPost;
import com.suse.service.community.entity.User;
import com.suse.service.community.service.DiscussPostService;
import com.suse.service.community.service.LikeService;
import com.suse.service.community.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 首页前端控制器
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-08-29 15:41
 */
@Controller
public class IndexControler {

    @Resource
    private UserService userService;

    @Resource
    private DiscussPostService discussPostService;

    @Resource
    private LikeService likeService;

    @GetMapping("/index.html")
    public String getIndexPage(Model model, Page page, @RequestParam(name = "order",defaultValue = "0") int order) {
        page.setTotal(discussPostService.getDiscussPostTotal(0));
        page.setPath("/index.html?order=" + order);
        List<DiscussPost> discussPostList = discussPostService.getDiscussPostList(0, page.getOffset(), page.getLimit(),order);
        List<Map<String,Object>> mapList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(discussPostList)) {
            for (DiscussPost discussPost : discussPostList) {
                Map<String,Object> map = new HashMap<>();
                map.put("post",discussPost);
                User user = userService.getUserById(discussPost.getUserId());
                map.put("user",user);
                // 点赞数
                long likeCount = likeService.getEntityLikeCount(EntityTypeConstant.POST, discussPost.getId());
                map.put("likeCount",likeCount);
                mapList.add(map);
            }
        }
        model.addAttribute("order",order);
        model.addAttribute("discussPostList",mapList);
        return "index";
    }

    @GetMapping("/")
    public String forwardIndex() {
        return "forward:/index.html";
    }

    @GetMapping("/error")
    public String getErrorPage() {
        return "error/500";
    }

}
